"""Mail alias views.

dn: mail=somealias@example.com,ou=mail_aliases,dc=example,dc=com
mail: somealias@example.com
hcpMaildrop: eric@huss.org

TODO:
- Constrain "mail" attribute to mail_aliases this user is a member of.
- Record which user this is for?
- Check for duplicate "mail" entries.


- Permissions:
  - "mail_alias" admin can edit any alias for that mail_alias.
  - user can edit any alias entry they created
  - users can only create "mail" entries for mail_aliases they are a member of.


"""

from django import forms
from hcp.auth.decorators import permission_required
from hcp.forms.custom import MyDynamicField, MyGroupedForm
from hcp.forms.grouped import FormSection
from hcp.forms.util import form_from_model
from hcp.jinja import render_to_response
from hcp.ldap_models import MailAlias, update_model_from_post
from hcp.tracking import HcpCallback
from hcp.util.json import JsonResponse

class MailAliasForm(MyGroupedForm):

    class Required(FormSection):

        label = 'Required Attributes'

        mail = MyDynamicField(forms.CharField(), label='Email Address')
        hcpMaildrop = MyDynamicField(forms.CharField(), label='Maildrop')

@permission_required('manage_mail_aliases')
def index(request):
    return render_to_response('mail_aliases/index.html', request=request)

@permission_required('manage_mail_aliases')
def mail_alias_list(request):
    mail_aliases = MailAlias.objects.all()
    data = [ {'mail':mail_alias.mail[0],
              'hcpMaildrop':mail_alias.hcpMaildrop[0],
              'dn':mail_alias.dn} for mail_alias in mail_aliases ]

    return JsonResponse({
        'mail_aliases': data,
    })

@permission_required('manage_mail_aliases')
def new(request):
    if request.method == 'POST':
        form = MailAliasForm(request.POST)

        if form.is_valid():
            mail_alias = MailAlias()
            fields = form.fields.keys()
            update_model_from_post(mail_alias, form.cleaned_data, fields)
            mail_alias.save(callback=HcpCallback(request.user.uid[0]))
            # XXX: Handle errors.
            # XXX: Make this a dialog instead of a separate page.
            return render_to_response('mail_aliases/created.html', {'mail_alias': mail_alias}, request=request)
    else:
        form = MailAliasForm()

    return render_to_response('mail_aliases/new.html',
        {'form': form,
        }, request=request)

@permission_required('manage_mail_aliases')
def edit(request, dn):
    mail_alias = MailAlias.objects.get_dn(dn)
    # XXX not found

    if request.method == 'POST':
        form = MailAliasForm(request.POST)
        if form.is_valid():
            update_model_from_post(mail_alias, form.cleaned_data, form.fields.keys())
            mail_alias.save(callback=HcpCallback(request.user.uid[0]))
            # XXX: Handle errors.

            return render_to_response('mail_aliases/edited.html', {'mail_alias': mail_alias}, request=request)
    else:
        form = form_from_model(MailAliasForm, mail_alias)

    return render_to_response('mail_aliases/edit.html',
        {'mail_alias': mail_alias,
         'form': form,
        },
        request=request)

@permission_required('manage_mail_aliases')
def remove(request, dn):
    mail_alias = MailAlias.objects.get_dn(dn)
    mail_alias.delete(callback=HcpCallback(request.user.uid[0]))
    return JsonResponse({
        'result': 'success',
    })
